package com.example.springboot2.repository;

import com.example.springboot2.entity.LaundryOrder;
import com.example.springboot2.entity.Merchant;
import com.example.springboot2.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 洗护订单Repository
 */
@Repository
public interface LaundryOrderRepository extends JpaRepository<LaundryOrder, Long>, JpaSpecificationExecutor<LaundryOrder> {

    /**
     * 根据订单号查找订单
     */
    Optional<LaundryOrder> findByOrderNo(String orderNo);

    /**
     * 根据商家查找订单
     */
    Page<LaundryOrder> findByMerchant(Merchant merchant, Pageable pageable);

    /**
     * 根据商家和状态查找订单
     */
    Page<LaundryOrder> findByMerchantAndStatus(Merchant merchant, LaundryOrder.LaundryOrderStatus status, Pageable pageable);

    /**
     * 根据客户查找订单
     */
    Page<LaundryOrder> findByCustomer(User customer, Pageable pageable);

    /**
     * 统计商家订单数量
     */
    long countByMerchant(Merchant merchant);

    /**
     * 统计商家指定状态订单数量
     */
    long countByMerchantAndStatus(Merchant merchant, LaundryOrder.LaundryOrderStatus status);

    /**
     * 统计商家指定时间范围内的订单数量
     */
    @Query("SELECT COUNT(lo) FROM LaundryOrder lo WHERE lo.merchant = :merchant AND lo.createdTime BETWEEN :startTime AND :endTime")
    long countByMerchantAndCreatedTimeBetween(@Param("merchant") Merchant merchant, 
                                              @Param("startTime") LocalDateTime startTime, 
                                              @Param("endTime") LocalDateTime endTime);

    /**
     * 统计商家指定时间范围内的销售额
     */
    @Query("SELECT COALESCE(SUM(lo.actualAmount), 0) FROM LaundryOrder lo WHERE lo.merchant = :merchant AND lo.status NOT IN ('CANCELLED', 'REFUNDED') AND lo.createdTime BETWEEN :startTime AND :endTime")
    BigDecimal sumActualAmountByMerchantAndCreatedTimeBetween(@Param("merchant") Merchant merchant, 
                                                              @Param("startTime") LocalDateTime startTime, 
                                                              @Param("endTime") LocalDateTime endTime);

    /**
     * 查找商家今日订单
     */
    @Query("SELECT lo FROM LaundryOrder lo WHERE lo.merchant = :merchant AND DATE(lo.createdTime) = DATE(CURRENT_TIMESTAMP)")
    List<LaundryOrder> findTodayOrdersByMerchant(@Param("merchant") Merchant merchant);
}
